package org.qydjk.console.controller.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.qydjk.common.controller.BaseController;
import org.qydjk.common.pojo.Coupon;
import org.qydjk.common.pojo.user.User;
import org.qydjk.common.pojo.user.UserCoupon;
import org.qydjk.common.util.StringUtil;
import org.qydjk.common.vo.EasyUIResponse;
import org.qydjk.common.vo.HibernatePage;
import org.qydjk.common.vo.autocomplete.AutoCompleteBean;
import org.qydjk.common.vo.autocomplete.AutoCompleteResponse;
import org.qydjk.console.vo.UserCouponBeen;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Lanan on 2018/1/3 0003.
 */
@Controller
@RequestMapping("/user/coupon")
public class UserCouponController extends BaseController {

    @RequestMapping("/index.do")
    public String userCouponIndex() {
        return "user/coupon/userCoupon";
    }

    @RequestMapping("/list.do")
    @ResponseBody
    public Object userCouponList(int page, int rows) {
        Integer count = 0;
        List<UserCouponBeen> userCoupons = new ArrayList<UserCouponBeen>();
        String sql = "SELECT uc.*, u.username as user_name, c.`name`, c.intro, c.provider_type, " +
                "c.suit_type, c.type, c.subtraction_money, c.money, c.discount, c.max_discount_money, " +
                "c.start_time, c.end_time " +
                "FROM qy_user_coupon uc, qy_coupon c, qy_user u " +
                "WHERE uc.coupon_id = c.id " +
                "AND uc.user_id = u.id";
        String countSql = "SELECT COUNT(uc.id) " +
                "FROM qy_user_coupon uc, qy_coupon c, qy_user u " +
                "WHERE uc.coupon_id = c.id " +
                "AND uc.user_id = u.id";
        sql += addWhereStr();
        countSql += addWhereStr();

        sql += " order by uc.update_time desc";

        try {
            userCoupons = baseService.findBeanBySQL(sql, UserCouponBeen.class, new HibernatePage(page, rows));
            count = baseService.getRecordCountSQL(countSql);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new EasyUIResponse(count, userCoupons);
    }

    private String addWhereStr() {
        String whereStr = "";
        whereStr += addStr("userId");
        return whereStr;
    }

    private String addStr(String keyStr) {
        String str = request.getParameter(keyStr);
        if (!StringUtil.isEmptyOrNull(str)) {
            return " AND uc.user_id = " + str;
        }
        return "";
    }

    @RequestMapping("/grant.do")
    @ResponseBody
    public Object userCouponGrant() {
        JSONObject resp = new JSONObject();
        Integer userId = Integer.valueOf(request.getParameter("userId"));
        if (userId == null) {
            resp.put("success", false);
            resp.put("msg", "用户信息出错!");
            return JSON.toJSON(resp);
        }
        Integer couponId = Integer.valueOf(request.getParameter("couponId"));
        if (couponId == null) {
            resp.put("success", false);
            resp.put("msg", "优惠券信息出错!");
            return JSON.toJSON(resp);
        }

        try {
            User user = baseService.get(User.class, userId.intValue());
            if (user.getId() == null) {
                resp.put("success", false);
                resp.put("msg", "用户信息出错!");
                return JSON.toJSON(resp);
            }
            Coupon coupon = baseService.get(Coupon.class, couponId);
            if (coupon.getId() == null) {
                resp.put("success", false);
                resp.put("msg", "优惠券信息出错!");
                return JSON.toJSON(resp);
            } else if (coupon.getRemainRepertory() <= 0){
                resp.put("success", false);
                resp.put("msg", "该优惠券数量不足!");
                return JSON.toJSON(resp);
            }
            Date date = new Date();
            int i = date.compareTo(coupon.getEndTime());
            if (i > 0) {
                resp.put("success", false);
                resp.put("msg", "该优惠券已过期, 无法发放!");
                return JSON.toJSON(resp);
            }

            coupon.setRemainRepertory(coupon.getRemainRepertory() - 1);
            baseService.update(coupon);

            UserCoupon userCoupon = new UserCoupon();
            userCoupon.setCouponId(coupon.getId());
            userCoupon.setUserId(user.getId());
            userCoupon.setUsed(1);
            userCoupon.setCreateTime(date);
            userCoupon.setUpdateTime(date);
            baseService.save(userCoupon);
            resp.put("success", true);
            resp.put("msg", "发放成功!");
        } catch (Exception e) {
            e.printStackTrace();
            resp.put("success", false);
            resp.put("msg", e.toString());
        }
        return JSON.toJSON(resp);
    }


    @RequestMapping("/delete.do")
    @ResponseBody
    public Object userCouponDelete(UserCoupon userCoupon) {
        JSONObject resp = new JSONObject();
        try {
            resp.put("success", true);
            baseService.delete(userCoupon);
        } catch (Exception e) {
            resp.put("success", false);
            resp.put("msg", e.toString());
            e.printStackTrace();
        }
        return JSON.toJSON(resp);
    }

    /**
     * 自动补全 优惠券信息
     */
    @RequestMapping("/autoCompleteData.do")
    @ResponseBody
    public Object userAutoCompleteData() {
        List<AutoCompleteBean> list = new ArrayList<AutoCompleteBean>();
        String query = request.getParameter("query");
//        query = StringUtil.iosToUTF8(query).trim();
        if (StringUtil.isEmptyOrNull(query)) {
            return new AutoCompleteResponse(list);
        }
        Date date = new Date();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = sf.format(date);
        String sql = "SELECT concat(name,'') AS `value`, concat(id,'') AS `data` FROM qy_coupon " +
                "WHERE `name` LIKE '%" + query + "%' " +
                "AND remain_repertory > 0 " +
                "AND end_time > '" + dateStr + "'";
        try {
            list = baseService.findBeanBySQL(sql, AutoCompleteBean.class, new HibernatePage(1, 10));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AutoCompleteResponse(list);
    }
}
